package com.huaao.micropolice.core.service.content.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huaao.micropolice.core.common.page.Page;
import com.huaao.micropolice.core.common.page.Parameter;
import com.huaao.micropolice.core.common.page.Sort;
import com.huaao.micropolice.core.model.content.Content;
import com.huaao.micropolice.core.repository.content.ContentDao;
import com.huaao.micropolice.core.service.content.ContentService;

@Service
public class ContentServiceImpl implements ContentService{

	@Autowired
	private ContentDao contentDao;
	@SuppressWarnings("unchecked")
	public List<Content> listContent(Page page){
		
		return contentDao.findByPage(Content.class, null, new Sort("lastUpdateTime", "desc"), page);
	}
	
	@Transactional
	public String  addContent(Content newContent){
		if(newContent.getSubject()!=null&&StringUtils.isBlank(newContent.getSubject().getId())){
			newContent.setSubject(null);
		}
		return contentDao.save(newContent);
	}
	
	@Transactional
	public void updateContent(Content content){
		
		contentDao.update(content);
	}
	
	@Transactional(readOnly=false)
	public void deleteContent(String id){
		contentDao.deleteById(Content.class,id);
	}

	@Override
	public Content get(String contentId) {
		// TODO Auto-generated method stub
		return (Content) contentDao.get(Content.class, contentId);
	}

	@Override
	public Long getCount() {
		// TODO Auto-generated method stub
		return contentDao.getCount("from Content c");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Content> listBySubjectId(String subjectId, Page page) {
		List<Parameter> params = new ArrayList<Parameter>();
		Parameter p = new Parameter();
		p.setField("subject.id");
		p.setSign("eq");
		p.setValue(subjectId);
		params.add(p);
		// TODO Auto-generated method stub
		return contentDao.findByPage(Content.class, params ,  new Sort("lastUpdateTime", "desc"), page);
	}

	@Override
	public Long getCountBySubjectId(String subjectId) {
		// TODO Auto-generated method stub
		return contentDao.getCount(" from Content c where c.subject.id = '"+subjectId+"'");
	}


}
